import { createApp, ref } from 'vue'
import userMemberDialog from '@/components/dialog/user-member-dialog.vue'
import userMemberChangeDialog from '@/components/dialog/user-member-change.vue'
import settingDialog from '@/components/dialog/setting-dialog.vue'
import downloadDialog from '@/components/dialog/download-dialog.vue'
import downloadErrorDialog from '@/components/dialog/download-error-dialog.vue'
import dialogSimple from '@/components/dialog/dialog-simple.vue'
import dialogQr from '@/components/dialog/dialog-qr.vue'
import dialogUserOverload from '@/components/dialog/user-overload-dialog.vue'

const useDialogPromiseHook = () => {
  const instance = ref<any>(null)
  const parent = ref<any>(null)

  const clear = () => {
    if (instance.value !== null) {
      instance.value.unmount(parent.value)
      document.body.removeChild(parent.value)
      instance.value = null
    }
  }

  const showDialog = (type: string, options?: any) => {
    if (instance.value !== null) clear()
    return new Promise((resolve, reject) => {
      const defaultOptions = {
        handleSuccess: (value: any,preventClose:boolean) => {
          if(!preventClose){
            clear()
          }
          resolve(value)
        },
        handleCancel: (value: any,preventClose:boolean) => {
          if(!preventClose){
            clear()
          }
          reject(value)
        },
        ...(options ?? {})
      }
      const _dialogMap = {
        member: userMemberDialog,
        memberChange:userMemberChangeDialog,
        setting: settingDialog,
        download: downloadDialog,
        downloadError: downloadErrorDialog,
        dialogSimple: dialogSimple,
        dialogQr: dialogQr,
        userOverload:dialogUserOverload
      }
      const _dialog = _dialogMap[type as keyof typeof _dialogMap]

      instance.value = createApp(_dialog, defaultOptions)
      parent.value = document.createElement('div')
      document.body.appendChild(parent.value)
      instance.value.mount(parent.value)
    })
  }

  return {
    showDialog
  }
}

export default useDialogPromiseHook
